package com.example.makerspace.manager;

import com.alibaba.fastjson.JSONObject;
import com.example.makerspace.dto.ResourceDTO;
import com.example.makerspace.dao.ResourceDAO;
import com.example.makerspace.domain.ResourceDO;
import com.example.makerspace.utils.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component

public class ResourceManager extends BaseManager<ResourceDO, ResourceDTO>{

    private final static String RESOURCE_PATH_PREFIX = "resource/";
  private  final  static  String   testHttpPrefix="https://119.45.199.13:3035/static/";

   private  final  static  String  devHttpPrefix="https://nism.ytcata.com:443/static/";

    @Resource
    private ResourceDAO resourceDAO;

    @PostConstruct
    public void init(){
        this.baseDAO = resourceDAO;
    }

    public JSONObject upload(ResourceDTO resourceDTO) {
        MultipartFile resource = resourceDTO.getResource();
        if(resource == null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("errno", 1);
            jsonObject.put("message", "图片为空");
            return jsonObject;
        }
        String path = FileUtils.saveMultipartFile(resource,
                FileUtils.staticPath + RESOURCE_PATH_PREFIX + resourceDTO.getResourceType());
        ResourceDO resourceDO = new ResourceDO();
        resourceDO.setResource(path);
        resourceDO.setResourceType(resourceDTO.getResourceType());
        addDO(resourceDO);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errno", 0);
        JSONObject data = new JSONObject();
        data.put("url", devHttpPrefix + FileUtils.getBriefPath(path));
        jsonObject.put("data", data);
        return jsonObject;
    }
}
